﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum UIFixedAspectMode
{
    none,
    fit,
    fill,
}

public class UITextureEx : UITexture
{
    string url;
    public UIFixedAspectMode mFixedAspectMode = UIFixedAspectMode.none;

    public override Vector4 drawingDimensions
    {
        get
        {
            Vector4 result = base.drawingDimensions;

            if (mFixedAspectMode != UIFixedAspectMode.none)
            {
                Texture tex = mainTexture;
                if (tex == null) return result;

                Rect rect = this.uvRect;
                Rect outer = new Rect(rect.x * tex.width, rect.y * tex.height, tex.width * rect.width, tex.height * rect.height);

                float outerRatio = Mathf.Abs(outer.width / outer.height);
                float w = result.z - result.x;
                float h = result.w - result.y;
                float dimensionsRatio = w / h;
                if ((mFixedAspectMode == UIFixedAspectMode.fill && outerRatio < dimensionsRatio) || (mFixedAspectMode == UIFixedAspectMode.fit && outerRatio > dimensionsRatio))
                {
                    float hh = w / outerRatio / 2;
                    float yc = (result.y + result.w) * 0.5f;
                    result.y = yc - hh;
                    result.w = yc + hh;
                }
                else if ((mFixedAspectMode == UIFixedAspectMode.fill && outerRatio > dimensionsRatio) || (mFixedAspectMode == UIFixedAspectMode.fit && outerRatio < dimensionsRatio))
                {
                    float hw = outerRatio * h / 2;
                    float xc = (result.x + result.z) * 0.5f;
                    result.x = xc - hw;
                    result.z = xc + hw;
                }
            }

            //            if (fixScreenEdge)
            //            {
            //                result.z = Mathf.Ceil(result.z);
            //                result.y = Mathf.Floor(result.y);
            //            }
            return result;
        }
    }

    public void SetTexture(string url)
    {
        SetTexture(url, null);
    }

    public void SetTexture(string url, Texture preloadTex)
    {
        if (this.url == url)
        {
            return;
        }

        HttpResourceManager.instance.Cancel(url, OnTextureLoaded);

        this.url = url;

        if (preloadTex != null)
        {
            this.mainTexture = preloadTex;
        }

        HttpResourceManager.instance.Load(url, LoadHttpResourceTask.ResourceType.texture, OnTextureLoaded);
    }

    void OnTextureLoaded(string url, Object tex)
    {
        if (tex != null)
        {
            this.mainTexture = tex as Texture2D;
        }
    }

    protected override void OnDestroy()
    {
        HttpResourceManager.instance.Cancel(url, OnTextureLoaded);
        url = null;

        base.OnDestroy();
    }
}
